<template>
  <div class="common-container">
    <div class="common-content">
      <!-- 订单状态和内容 -->
      <el-card class="order-card" v-if="order">
        <!-- 订单状态 -->
        <div class="order-status" :class="getStatusClass(order.status)">
          <div class="status-text">订单详情 - {{ getStatusText(order.status) }}</div>
          <div v-if="order.status === 1" class="status-actions">
            <el-button type="primary" @click="goToPayment">去支付</el-button>
            <el-button @click="cancelOrder">取消订单</el-button>
          </div>
          <div v-else-if="order.status === 2" class="status-actions">
            <el-button type="primary" @click="confirmReceipt">确认收货</el-button>
          </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="section">
          <h3 class="section-title">订单信息</h3>
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单编号:</span>
              <span class="value">{{ order.orderNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ formatDate(order.createTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付时间:</span>
              <span class="value">{{ order.payTime ? formatDate(order.payTime) : '未支付' }}</span>
            </div>
            <div class="info-item">
              <span class="label">发货时间:</span>
              <span class="value">{{ order.deliveryTime ? formatDate(order.deliveryTime) : '未发货' }}</span>
            </div>
            <div class="info-item">
              <span class="label">完成时间:</span>
              <span class="value">{{ order.completeTime ? formatDate(order.completeTime) : '未完成' }}</span>
            </div>
            <div class="info-item">
              <span class="label">备注:</span>
              <span class="value">{{ order.remark || '无' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 收货信息 -->
        <div class="section">
          <h3 class="section-title">收货信息</h3>
          <div class="address-info" v-if="order.address">
            <div class="address-header">
              <span class="address-name">{{ order.address.name }}</span>
              <span class="address-phone">{{ order.address.phone }}</span>
            </div>
            <div class="address-content">
              {{ order.address.province }} {{ order.address.city }} {{ order.address.district }} {{ order.address.detail }}
            </div>
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="section">
          <h3 class="section-title">商品信息</h3>
          <el-table :data="order.orderItems" style="width: 100%" border>
            <el-table-column prop="productName" label="商品名称" min-width="200" align="center">
              <template slot-scope="scope">
                <div class="goods-info-cell">
                  <img :src="scope.row.goodsImg" alt="" class="goods-small-img">
                  <span>{{ scope.row.goodsName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100" align="center">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" align="center"></el-table-column>
            <el-table-column label="小计" width="100" align="center">
              <template slot-scope="scope">
                <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 金额信息 -->
        <div class="section">
          <h3 class="section-title">金额信息</h3>
          <div class="amount-info">
            <div class="amount-item">
              <span>商品总价:</span>
              <span>¥{{ order.totalPrice.toFixed(2) }}</span>
            </div>
            <div class="amount-item">
              <span>运费:</span>
              <span>¥0.00</span>
            </div>
            <div class="amount-item total">
              <span>实付金额:</span>
              <span class="total-price">¥{{ order.totalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div v-if="order.status === 4" class="section">
          <h3 class="section-title">商品评价</h3>
          <el-button type="primary" @click="goToComment">评价商品</el-button>
        </div>
      </el-card>
      
      <!-- 加载中 -->
      <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "OrderDetail",
  data() {
    return {
      order: null,
      loading: true
    };
  },
  created() {
    this.loadOrderDetail();
  },
  methods: {
    loadOrderDetail() {
      const orderId = this.$route.query.orderId;
      if (!orderId) {
        this.$message.warning('订单ID不存在');
        this.$router.push('/front/orderList');
        return;
      }
      
      this.loading = true;
      this.request.get(`/orders/${orderId}`).then(res => {
        this.loading = false;
        
        if (res.code === 200 && res.data) {
          // 字段映射，适配前端展示
          const orderData = res.data;
          this.order = {
            ...orderData,
            orderNo: orderData.no || orderData.orderNo,
            orderItems: orderData.details ? orderData.details.map(item => ({
              goodsId: item.goodsId || item.productId,
              goodsName: item.goodsName || item.productName,
              goodsImg: item.imgUrl || item.img || item.productImg,
              price: item.price,
              quantity: item.num || item.quantity
            })) : []
          };
        } else {
          this.$message.error(res.msg || '获取订单详情失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取订单详情失败');
      });
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '已取消',
        1: '待支付',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已退款'
      };
      return statusMap[status] || '未知状态';
    },
    
    getStatusClass(status) {
      const statusClassMap = {
        0: 'status-canceled',
        1: 'status-pending',
        2: 'status-processing',
        3: 'status-shipped',
        4: 'status-completed',
        5: 'status-refunded'
      };
      return statusClassMap[status] || '';
    },
    
    goToPayment() {
      this.$router.push({
        path: '/front/payment',
        query: {
          orderId: this.order.id,
          amount: this.order.totalPrice
        }
      });
    },
    
    cancelOrder() {
      this.$confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用管理端的更新状态接口
        this.request.put(`/orders/${this.order.id}/status`, { status: '已关闭' }).then(res => {
          if (res.code === 200) {
            this.$message.success('订单已取消');
            this.loadOrderDetail();
          } else {
            this.$message.error(res.msg || '取消订单失败');
          }
        }).catch(() => {
          this.$message.error('取消订单失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    confirmReceipt() {
      this.$confirm('确认已收到商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        // 使用管理端的更新状态接口
        this.request.put(`/orders/${this.order.id}/status`, { status: '已完成' }).then(res => {
          if (res.code === 200) {
            this.$message.success('确认收货成功');
            this.loadOrderDetail();
          } else {
            this.$message.error(res.msg || '确认收货失败');
          }
        }).catch(() => {
          this.$message.error('确认收货失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    goToComment() {
      this.$router.push({
        path: '/front/comment',
        query: {
          orderId: this.order.id
        }
      });
    },
    
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 20px;
}

.common-content {
  margin-bottom: 20px;
}

.order-card {
  background-color: #fff;
}

.order-status {
  padding: 20px;
  text-align: center;
  margin-bottom: 30px;
  border-radius: 4px;
}

.status-text {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.status-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 不同状态的样式 */
.status-pending {
  background-color: #e6f7ff;
}

.status-pending .status-text {
  color: #1890ff;
}

.status-processing {
  background-color: #fff7e6;
}

.status-processing .status-text {
  color: #fa8c16;
}

.status-shipped {
  background-color: #f6ffed;
}

.status-shipped .status-text {
  color: #52c41a;
}

.status-completed {
  background-color: #f6ffed;
}

.status-completed .status-text {
  color: #52c41a;
}

.status-canceled {
  background-color: #f5f5f5;
}

.status-canceled .status-text {
  color: #8c8c8c;
}

.status-refunded {
  background-color: #fff1f0;
}

.status-refunded .status-text {
  color: #ff4d4f;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
}

.order-info {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 100px;
  color: #909399;
}

.value {
  color: #303133;
}

.address-info {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.address-name {
  margin-right: 20px;
  color: #303133;
}

.address-phone {
  color: #606266;
}

.address-content {
  color: #606266;
  line-height: 1.5;
}

.goods-info-cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.goods-small-img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin-right: 10px;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.amount-info {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  text-align: right;
}

.amount-item {
  margin-bottom: 10px;
  color: #606266;
}

.amount-item.total {
  font-weight: bold;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e4e7ed;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}
</style>